/*!
 * Component: components/Index/index
 * License: MIT
 * Created: 2019-12-23 13:59
 */

import { topicApi } from '/api/topic'
import { $event } from '/utils'
import { onNews } from '/store/mutations'
import { GlobalData } from '/store/state'

Component({
  /**
   * Component properties
   */
  properties: {
    currencyName: { type: String, value: GlobalData.currencyName },
    topic: { type: Object, value: {} as DomoTopic },
    user: { type: Object, value: {} as DomoUser },
    ishomepage: { type: Boolean, value: false },
  },

  /**
   * Component initial data [private]
   */
  data: {
    paytoast: true,
  },

  /**
   * lifecycle of component
   */
  lifetimes: {},

  /**
   * Component methods
   */
  methods: {
    // 跳转到话题
    goToDetail(e: any) {
      const {
        target: {
          dataset: { topic },
        },
      } = e
      if (topic) {
        wx.navigateTo({ url: `/pages/topic/detail/detail?topicId=${topic.id}` })
      }
    },
    /**
     * 加入圈子
     */
    async joinTopic(e: any) {
      const {
        currentTarget: {
          dataset: { topic },
        },
      } = e
      /** 需要审核的加圈申请，弹出订阅消息 */
      if (topic.join_mode === 'need-audit' && topic.expense === 0) {
        try {
          await onNews(['{{CIRCLE_JOINED}}', '{{CIRCLE_REFUSED}}'])
        } catch (error) {
          wx.showToast({ title: '请配置正确的订阅消息key，具体位置在package.json', icon: 'none' })
        }
      }
      const paytoast = this.data.paytoast
      /** 付费圈子的扣费提醒 */
      if (topic.expense > 0) {
        //这里是付费的提示框
        return $event.emit('erorr:integral', { paytoast, topic })
      }
      topicApi
        .followTopic(topic.id)
        .then(() => {
          topic.join_mode === 'need-audit' && topic.expense === 0
            ? // eslint-disable-next-line require-atomic-updates
            (topic.apply_for_status = 'waiting')
            : // eslint-disable-next-line require-atomic-updates
            (topic.has_followed = true)
          $event.emit('after:joinTopic', topic)
          if (topic.join_mode !== 'need-audit') {
            wx.navigateTo({ url: `/pages/topic/detail/detail?topicId=${topic.id}` })
          }
        })
        .catch((res) => {
          if (res.data.message === '积分不足') {
            return $event.emit('erorr:integral', { paytoast, topic })
          } else {
            wx.showToast({
              title: '加入失败,稍后重试',
              icon: 'none',
            })
          }
        })
    },
    /** 赚积分 */
    toCurrency() {
      wx.switchTab({
        url: '/pages/currency/currency',
      })
    },
    /** 充值 */
    toRecharge() {
      this.close()
      wx.navigateTo({
        url: '/pages/recharge/recharge',
      })
    },
    /** 关闭弹窗 */
    close() {
      this.setData({
        payToast: false,
      })
    },
    /** 进入审核申请的页面 */
    toMerber() {
      wx.navigateTo({
        url: `/pages/topic/member/member?id=${this.data.topic.id}&iscreater=${true}`,
      })
    },
  },
})
